package com.leyou.lock;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 *
 */
public class RedisLockImpl implements RedisLock{
    private StringRedisTemplate redisTemplate;

    private String key;

    public RedisLockImpl(StringRedisTemplate redisTemplate,String key){
        this.key = key;
        this.redisTemplate =redisTemplate;
    }

    /**
     * 锁对应的值，无意义，写为1
     */
    private static final String value = "1";

    @Override
    public boolean lock(long locktime) {
        //setIfAbsent()方法底层就是发送setnx命令
        /**
         * setnx key value:
             如果该key不存在，则设置key和value到redis，返回1
             如果该key存在，无法设置key和value，返回0
         */
        // 尝试获取锁
        Boolean boo = redisTemplate.opsForValue().setIfAbsent(key, value, locktime, TimeUnit.SECONDS);
        // 判断结果
        return boo != null && boo;
    }

    @Override
    public void unlock() {
        // 删除key即可释放锁
        redisTemplate.delete(key);
    }
}
